﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Cimbalino.Phone.Toolkit.Services;
using DepSoft.Mobile.WP8.FollwIt.Messages;
using FollwItPortable;
using FollwItPortable.Model;
using GalaSoft.MvvmLight.Messaging;

namespace DepSoft.Mobile.WP8.FollwIt.ViewModel
{
    public class SeriesViewModel : AppCreativityViewModelBase
    {
        private IFollwItClient _follwItClient;

        private ObservableCollection<FollwItTvShow> _series = new ObservableCollection<FollwItTvShow>();
        public ObservableCollection<FollwItTvShow> Series
        {
            get { return _series; }
            set
            {
                if (value == _series)
                    return;

                _series = value;
                RaisePropertyChanged();
            }
        }

        public SeriesViewModel(IFollwItClient follwItClient, INavigationService navigationService, IMessenger messenger)
            : base(navigationService, messenger)
        {
            _follwItClient = follwItClient;

            messenger.Register<FollwItUserMessage>(this, Tokens.ForSeries, async message => RefreshLayout(message.UserName));
        }

        private async Task RefreshLayout(string userName)
        {
            this.IsBusy = true;
            this.Series.Clear();
            List<FollwItTvShow> series = new List<FollwItTvShow>();
            try
            {
                series = await Task.Run(() => _follwItClient.GetUserTvCollectionAsync(userName));
            }
            catch (Exception e)
            {
                
            }
         
            foreach(FollwItTvShow tvShow in series)
                this.Series.Add(tvShow);

            this.IsBusy = false;
        }
    }
}
